import Flutter
import UIKit
import Foundation
import IOSSecuritySuite


public class SecurityDefendWallPlugin: NSObject, FlutterPlugin {
  public static func register(with registrar: FlutterPluginRegistrar) {
    let channel = FlutterMethodChannel(name: "security_defend_wall", binaryMessenger: registrar.messenger())
    let instance = SecurityDefendWallPlugin()
    registrar.addMethodCallDelegate(instance, channel: channel)
  }

  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
    switch call.method {
    case "getPlatformVersion":
      result("iOS " + UIDevice.current.systemVersion)
      break
    case "isTampered":
       guard let args = call.arguments as? [String: Any],
             let teamId = args["teamId"] as? String else {
                result(true)
                break
             }
        let tampered = checkInfoPlistTampering()
        if (tampered) {
            result(true)
            break
        }
        let tid = getTeamIdentifier() ?? ""
        result(tid != teamId)
        break
    case "isRooted":
        var detected = IOSSecuritySuite.amIJailbroken()
        if (detected) {
            result(true)
            break
        }
        detected = IOSSecuritySuite.amIReverseEngineered()
        result(detected)
        break
    case "isEmulator":
        var detected = IOSSecuritySuite.amIRunInEmulator()
        result(detected)
        break
    case "isDebugged":
        var detected = IOSSecuritySuite.amIDebugged()
        if (detected) {
            result(true)
            break
        }
        detected = IOSSecuritySuite.isParentPidUnexpected()
        if (detected) {
            result(true)
            break
        }
        detected = IOSSecuritySuite.amIProxied()
        result(detected)
        break
    default:
      result(FlutterMethodNotImplemented)
    }
  }
    
  // Info.plist篡改检测
  private func checkInfoPlistTampering() -> Bool {
      guard let infoDict = Bundle.main.infoDictionary else {
          return true
      }
      return infoDict["SignerIdentity"] != nil || infoDict["UIDeviceFamily"] == nil
  }

  //开发者团队ID
  private func getTeamIdentifier() -> String? {
      let query: [String: Any] = [
              kSecClass as String: kSecClassGenericPassword,
              kSecAttrAccount as String: "bundleSeedID",
              kSecAttrService as String: "",
              kSecReturnAttributes as String: true
          ]

      var item: CFTypeRef?
      guard SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess,
            let accessGroup = (item as? [String: Any])?[kSecAttrAccessGroup as String] as? String
      else { return nil }
      return accessGroup.components(separatedBy: ".").first
  }
}
